package service

import (
	"mime/multipart"
	"path"
	"sharePicture/models/dao"
	"sharePicture/models/dto"
	"strings"

	"github.com/gin-gonic/gin"
)

// 上传图片并返回信息
func UploadPicture(uid int, groups []int, art string, fils []*multipart.FileHeader, c *gin.Context) (dao.PictureDao, bool) {
	save := ""
	//保存上传文件
	for _, file := range fils {
		fname := file.Filename
		save = save + "&" + fname //将图片名字冗余存储以&分隔
		dst := path.Join("D:/picture", fname)
		c.SaveUploadedFile(file, dst)
	}
	picture := dao.PictureDao{}
	sql := "insert into picture(data,note,path,user_id) values(now(),?,?,?)"
	row := DB.Exec(sql, art, save, uid)
	if row.RowsAffected > 0 {
		var pid int
		DB.Raw("select LAST_INSERT_ID()").Scan(&pid)
		sql := "insert into picture_groups(picture_id,groups_id) value(?,?)"
		for _, groupId := range groups {
			row := DB.Exec(sql, pid, groupId)
			if row.RowsAffected <= 0 {
				return picture, false
			}
		}
		DB.Raw("select * from picture where picture_id=?", pid).Scan(&picture)
		return picture, true
	}
	return picture, false

}

// 返回标签集合
func GetGroupsList() ([]dao.GroupsDao, bool) {
	listGroups := []dao.GroupsDao{}
	row := DB.Raw("select groups_id,name from groups").Scan(&listGroups)
	if row.RowsAffected > 0 {
		return listGroups, true
	} else {
		return listGroups, false
	}
}

func GetPictureInfo(uid int, pid int) (dto.PictureDto, bool) {
	pd := dao.PictureDao{}
	PictureDto := dto.PictureDto{}
	row := DB.Raw("select * from picture where picture_id=?", pid).Scan(&pd)
	if row.RowsAffected > 0 {
		gList := []dao.GroupsDao{}
		var gid []int
		DB.Raw("select groups_id from picture_groups where picture_id=?", pid).Scan(&gid)
		DB.Where("groups_id in ?", gid).Find(&gList)
		PictureDto.Groups = gList
		PictureDto.Date = pd.Data
		PictureDto.Collect = pd.Collect
		PictureDto.LikeCount = pd.LikeCount
		PictureDto.Note = pd.Note
		PictureDto.TransPond = pd.TransPond
		PictureDto.Path = strings.Split(pd.Path, "&")
		u := dao.User{}
		DB.Raw("select * from user where user_id=?", pd.UserId).Scan(&u)
		u.Password = ""
		PictureDto.User = u
		var count int
		DB.Raw("select count(*) from comment where picture_id=?", pid).Scan(&count)
		PictureDto.Total = count
		var c1, c2 int
		DB.Raw("select count(*) from user_picture where user_id =? and picture_id=? and opt=1", uid, pid).Scan(&c1)
		DB.Raw("select count(*) from user_picture where user_id =? and picture_id=? and opt=2", uid, pid).Scan(&c2)
		if c1 > 0 {
			PictureDto.LikeFlag = true
		}
		if c2 > 0 {
			PictureDto.CollectFlag = true
		}
		return PictureDto, true
	}
	return PictureDto, false
}
